package com.zucai365.football.service.impl;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import net.sf.json.JSONArray;

import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import com.wcj.common.service.impl.WcjServiceImpl;
import com.zucai365.football.bean.FootballPlayerBean;
import com.zucai365.football.bean.FootballTeamBean;
import com.zucai365.football.bean.LianSaiBean;
import com.zucai365.football.bean.LianSaiYearBean;
import com.zucai365.football.bean.TeamPlayerBean;
import com.zucai365.football.dao.FootballPlayerDao;
import com.zucai365.football.service.FootballPlayerService;
import com.zucai365.football.service.FootballTeamService;
import com.zucai365.football.service.LianSaiService;
import com.zucai365.football.service.LianSaiYearService;
import com.zucai365.football.service.TeamPlayerService;
import com.zucai365.football.utils.Constant;
import com.zucai365.football.utils.ZuCaiUtils;

@Service("footballPlayerService")
public class FootballPlayerServiceImpl extends WcjServiceImpl<FootballPlayerBean> implements FootballPlayerService{
	
	@Autowired
	@Qualifier("footballPlayerDao")
	private FootballPlayerDao footballPlayerDao;

	public FootballPlayerDao getFootballPlayerDao() {
		return footballPlayerDao;
	}

	public void setFootballPlayerDao( FootballPlayerDao footballPlayerDao ) {
		this.footballPlayerDao = footballPlayerDao;
	}
	
	@Autowired
	@Qualifier("footballTeamService")
	private FootballTeamService footballTeamService;
	
	public FootballTeamService getFootballTeamService() {
		return footballTeamService;
	}

	public void setFootballTeamService(FootballTeamService footballTeamService) {
		this.footballTeamService = footballTeamService;
	}
	
	@Autowired
	@Qualifier("lianSaiService")
	private LianSaiService lianSaiService;

	public LianSaiService getLianSaiService() {
		return lianSaiService;
	}

	public void setLianSaiService(LianSaiService lianSaiService) {
		this.lianSaiService = lianSaiService;
	}
	
	@Autowired
	@Qualifier("lianSaiYearService")
	private LianSaiYearService lianSaiYearService;
	
	public LianSaiYearService getLianSaiYearService() {
		return lianSaiYearService;
	}

	public void setLianSaiYearService(LianSaiYearService lianSaiYearService) {
		this.lianSaiYearService = lianSaiYearService;
	}
	
	@Autowired
	@Qualifier("teamPlayerService")
	private TeamPlayerService teamPlayerService;
	
	public TeamPlayerService getTeamPlayerService() {
		return teamPlayerService;
	}

	public void setTeamPlayerService(TeamPlayerService teamPlayerService) {
		this.teamPlayerService = teamPlayerService;
	}
	
	/**
	 * 保存一个球队的球员信息
	 */
	@Override
	public void saveFootplayer(Long lianSaiYearId, Long lianSaiId,Long footballTeamId) {
		
		FootballTeamBean footballTeam = this.footballTeamService.get( footballTeamId );
		LianSaiBean liansai = ZuCaiUtils.getLianSaiById( lianSaiId );
		LianSaiYearBean liansaiYear = ZuCaiUtils.getLianSaiYearById( lianSaiYearId );
		
		String path = Constant.WAR_PATH + "teamInfo/" + liansai.getEnglishName()+ "/";
		String jsPath = path + "player_" + footballTeam.getFootballTeamName() + "_"+ liansaiYear.getLiansaiYear() +".js";
		
		//守门员goalkeeper
		//后卫rearguard
		//中场midfielder
		//前锋vanguard
		File jsFile = new File( jsPath );
		FileInputStream stream = null;
		InputStreamReader reader = null;
		BufferedReader br = null;
		
		
		List<FootballPlayerBean> footballPlayerList = new ArrayList<FootballPlayerBean>();
		try {
			stream = new FileInputStream( jsFile );
			reader = new InputStreamReader( stream, "utf-8" );
			br = new BufferedReader( reader );
			
			String s = "";
			while (( s = br.readLine()) != null ) {			
				if( s.startsWith( "var goalkeeper" ) ){
					parsePlayerJson( s,footballPlayerList,"守门员" ,footballTeam , liansai , liansaiYear ,true ,null );
				}else if( s.startsWith( "var rearguard" ) ){
					parsePlayerJson( s,footballPlayerList,"后卫" ,footballTeam , liansai , liansaiYear ,true ,null);
				}else if( s.startsWith( "var midfielder" ) ){
					parsePlayerJson( s,footballPlayerList,"中场" ,footballTeam , liansai , liansaiYear ,true ,null);
				}else if( s.startsWith( "var vanguard" ) ){
					parsePlayerJson( s,footballPlayerList,"前锋" ,footballTeam , liansai , liansaiYear ,true ,null);
				}else{
					continue;
				}
			}
			
		} catch ( Exception e) {
			e.printStackTrace();
			throw new RuntimeException( e.getCause() );
		}finally{
			try {
				stream.close();
				reader.close();
				br.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		
		this.footballPlayerDao.saveAll( footballPlayerList );
		this.teamPlayerService.saveTeamPlayer(footballTeam, liansai, liansaiYear, footballPlayerList);
	}
	
	private void parsePlayerJson( String line , List<FootballPlayerBean> footballPlayerList , String position 
			, FootballTeamBean footballTeam ,LianSaiBean liansai ,LianSaiYearBean liansaiYear , boolean isParse , String pid ){
		
		//球队球员json字符串
		String playerJson = line.split( "=" )[1].trim() ;
		playerJson = playerJson.substring( 0, playerJson.length()-1 );
		
		JSONArray jsonArray = JSONArray.fromObject( playerJson );
		for( int i=0;i<jsonArray.size();i++ ){
			JSONArray playerArray = (JSONArray)jsonArray.get(i);
			
			//球员ID
			String playerId = playerArray.getString(0);
			
			//球员号码
			int jerseyNumber = -1 ;
			
			//简体姓名
			String chineseName = playerArray.getString( 2 );
			
			try{
				jerseyNumber = playerArray.getInt(1);
			}catch( Exception e ){
				System.out.println( "获取" + chineseName + "的球衣号码失败！" );
				continue;
			}
			
			//繁体姓名
			String ftName = playerArray.getString( 3 );
			
			//英文名
			String englishName = playerArray.getString( 4 );

			String realPlayerId = getCode( playerId.trim() );
			String playerUrl = "http://info.bet007.com/cn/team/player.aspx?playerid="+realPlayerId+"&TeamID="+footballTeam.getBet007Id();
			
			//如果
			if( !isParse && !realPlayerId.equals( pid ) ){
				continue;
			}
			
			FootballPlayerBean footballPlayer = getFootballPlayer( realPlayerId.trim() );
			
			if( footballPlayer == null ){
				footballPlayer = new FootballPlayerBean();
			}
			
			footballPlayer.setEnglishName(englishName);
			footballPlayer.setFtName(ftName);			
			footballPlayer.setPlayerName( chineseName );
			footballPlayer.setPlayerId( realPlayerId.trim() );
			//todo 球员图片地址
			
			if( isParse ){ //不需要抓取信息
				String msg = "";
				try {
					msg = ZuCaiUtils.getUrlContent( playerUrl , "utf-8" );
					Thread.sleep( 3000 );
				} catch (Exception e) {
					e.printStackTrace();
				}
							
				try{
					
					Document doc = Jsoup.parse( msg );
					Elements elements = doc.getElementsByClass( "tdlink" );
								
					doc = Jsoup.parse( elements.toString() );
					elements = doc.getElementsByTag( "strong" );
					
					footballPlayer.setNationality( elements.get(3).text() );
					footballPlayer.setBodyWeight( elements.get(4).text() );
					footballPlayer.setHeight( elements.get(5).text() );
					footballPlayer.setBirthay( elements.get(7).text() );
				}catch( Exception ex ){
					//ex.printStackTrace();
				}
			}
			
			
			footballPlayer.setJerseyNumber(jerseyNumber);
			footballPlayer.setPosition( position );
			
			footballPlayerList.add( footballPlayer );
		}
		
	}
	
	

	private String getCode( String playerID ) {
		StringBuffer arrID = new StringBuffer();
		for ( int i = 0; i < playerID.length(); i++ ) {
			int a = Integer.parseInt( playerID.charAt(i)+"" );
			switch (a) {
				case 0: arrID.append( decrypt2(0) ); break;
				case 4: arrID.append( decrypt2(1) ); break;
				case 5: arrID.append( decrypt2(2) ); break;
				case 3: arrID.append( decrypt2(3) ); break;
				case 6: arrID.append( decrypt2(4) ); break;
				case 9: arrID.append( decrypt2(5) ); break;
				case 7: arrID.append( decrypt2(6) ); break;
				case 1: arrID.append( decrypt2(7) ); break;
				case 2: arrID.append( decrypt2(8) ); break;
				case 8: arrID.append( decrypt2(9) ); break;
			}
		}
		return arrID.toString();
	}
	
	private String decrypt2( int data ){
		int b = (7 * (data - 6) % 10 + 10) % 10;
		return b + "" ;
	}

	/**
	 * 查询球员
	 */
	@Override
	public FootballPlayerBean getFootballPlayer( String playerId ) {

//		DetachedCriteria criteria = DetachedCriteria.forClass( FootballPlayerBean.class, "footballPlayer" );
//	
//		criteria.add( Restrictions.eq( "footballPlayer.playerId", playerId ) );
//		
//		List<FootballPlayerBean> list = 
//		if( list.size() > 1){
//			throw new RuntimeException( "每个球队的球员姓名不能重名！" );
//		}
//		
//		if( list.isEmpty() ){
//			return null;
//		}
//		
//		return list.get(0);
		
		try{
			return this.footballPlayerDao.findUniqueObj( "playerId", playerId );
		}catch( Exception ex ){
			return null;
		}
	}
	
	@Override
	public void updateTeamPlayer( TeamPlayerBean teamPlayer ) {

		FootballPlayerBean footballPlayer = this.footballPlayerDao.get( teamPlayer.getFootballPlayer().getId() );
		
		FootballTeamBean footballTeam = teamPlayer.getFootballTeam();
		LianSaiBean liansai = ZuCaiUtils.getLianSaiById( teamPlayer.getLiansai().getId() );
		LianSaiYearBean liansaiYear = ZuCaiUtils.getLianSaiYearById( teamPlayer.getLiansaiYear().getId() );
		
		String path = Constant.WAR_PATH + "teamInfo/" + liansai.getEnglishName()+ "/";
		String jsPath = path + "player_" + footballTeam.getFootballTeamName() + "_"+ liansaiYear.getLiansaiYear() +".js";
		
		//守门员goalkeeper
		//后卫rearguard
		//中场midfielder
		//前锋vanguard
		File jsFile = new File( jsPath );
		FileInputStream stream = null;
		InputStreamReader reader = null;
		BufferedReader br = null;
		
		
		List<FootballPlayerBean> footballPlayerList = new ArrayList<FootballPlayerBean>();
		try {
			stream = new FileInputStream( jsFile );
			reader = new InputStreamReader( stream, "utf-8" );
			br = new BufferedReader( reader );
			
			String s = "";
			while (( s = br.readLine()) != null ) {			
				if( s.startsWith( "var goalkeeper" ) ){
					parsePlayerJson( s,footballPlayerList,"守门员" ,footballTeam , liansai , liansaiYear , false ,footballPlayer.getPlayerId() );
				}else if( s.startsWith( "var rearguard" ) ){
					parsePlayerJson( s,footballPlayerList,"后卫" ,footballTeam , liansai , liansaiYear , false ,footballPlayer.getPlayerId() );
				}else if( s.startsWith( "var midfielder" ) ){
					parsePlayerJson( s,footballPlayerList,"中场" ,footballTeam , liansai , liansaiYear , false ,footballPlayer.getPlayerId() );
				}else if( s.startsWith( "var vanguard" ) ){
					parsePlayerJson( s,footballPlayerList,"前锋" ,footballTeam , liansai , liansaiYear , false ,footballPlayer.getPlayerId() );
				}else{
					continue;
				}
			}
			
		} catch ( Exception e) {
			e.printStackTrace();
			throw new RuntimeException( e.getCause() );
		}finally{
			try {
				stream.close();
				reader.close();
				br.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		

		for( FootballPlayerBean player : footballPlayerList ){
			if( player.getPlayerId().equals( footballPlayer.getPlayerId() ) ){
				
				footballPlayer.setEnglishName( player.getEnglishName() );
				footballPlayer.setFtName( player.getFtName() );			
				footballPlayer.setPlayerName( player.getPlayerName() );
				footballPlayer.setJerseyNumber( player.getJerseyNumber() );
				footballPlayer.setPosition( player.getPosition() );
				
				break;
			}
		}
		
		String playerUrl = "http://info.bet007.com/cn/team/player.aspx?playerid="+ footballPlayer.getPlayerId() +"&TeamID="+footballTeam.getBet007Id();
		teamPlayer.setPlayerUrl( playerUrl );
		teamPlayer.setPlayerName( footballPlayer.getPlayerName() );
		teamPlayer.setJerseyNumber( footballPlayer.getJerseyNumber() );
		teamPlayer.setPosition( footballPlayer.getPosition() );
		
		String msg = "";
		try {
			msg = ZuCaiUtils.getUrlContent( playerUrl , "utf-8" );
		} catch (Exception e) {
			e.printStackTrace();
		}
		Document doc = Jsoup.parse( msg );
		Elements elements = doc.getElementsByClass( "tdlink" );
					
		doc = Jsoup.parse( elements.toString() );
		elements = doc.getElementsByTag( "strong" );
		
		try{
			footballPlayer.setNationality( elements.get(3).text() );
			footballPlayer.setBodyWeight( elements.get(4).text() );
			footballPlayer.setHeight( elements.get(5).text() );
			footballPlayer.setBirthay( elements.get(7).text() );
			
			this.teamPlayerService.saveOrUpdate( teamPlayer );
			this.footballPlayerDao.saveOrUpdate( footballPlayer );
			
			
		}catch( Exception ex ){
			
		}
		
	}
}
